#
#  MolVizGui.py
#  PyMol Plugin
#
#  Created by Christian Muise on 25/01/08.
#  Copyright (c) 2008 Christian Muise. All rights reserved.
#

import threading, sys, time, wx, socket, re
from MolVizGeneratedGui import GUI

class MolVizGui(threading.Thread):
	def __init__(self, gui):
		threading.Thread.__init__(self)
		
		self.gui = gui
		self.frame_rate_in = ''
		self.frame_rate_out = ''
		
		self.message_pattern = re.compile(r'UPDATE:(.+);(.+);(.+);(.+);(.+);(.+);(.+);(.+);(.+);')
		
		
	def run(self):
		running = 1
		while running:
		
			#-- Update the volatile values - the rest can be updated when auto calibrated
			self.gui.text_ctrl_fpsIn.SetValue(self.frame_rate_in)
			self.gui.text_ctrl_fpsOut.SetValue(self.frame_rate_out)
			
			time.sleep(1)
	
	def updateGui(self, update_string):
		#--- Update all of the values
		result = update_string.rstrip(' ')
		result = result.rstrip('\n')
		if (result != ''):
			(accelRotAng, accelRotFov, rotWt, zmWt, zmRat, maxErr, errThresh, scrPlace, scrRat) = self.message_pattern.search(result).groups()
			self.gui.text_ctrl_acceleratedRotationAngle.SetValue(accelRotAng)
			self.gui.text_ctrl_acceleratedRotationFov.SetValue(accelRotFov)
			self.gui.text_ctrl_zoomRatio.SetValue(zmRat)
			self.gui.text_ctrl_errorThreshold.SetValue(errThresh)
			self.gui.text_ctrl_screenPlacementRatio.SetValue(scrRat)
			self.gui.slider_rotationWeight.SetValue(int(rotWt))
			self.gui.slider_zoomWeight.SetValue(int(zmWt))
			self.gui.slider_maxError.SetValue(int(maxErr))
			self.gui.combo_box_screenPlacement.SetSelection(int(scrPlace))
			
	
	def sendChange(self, change):
		mySocket = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
		mySocket.connect (('localhost', 4441))
		mySocket.send(change)
		mySocket.close()
		
class InputHandler(threading.Thread):
	def __init__(self, gui, frame):
		threading.Thread.__init__(self)
		
		self.gui_handler = gui
		self.frame = frame
						
		
	def run(self):
		
		time.sleep(2)
		self.frame.setProxy(self.gui_handler)
		
		update_message = re.compile(r'UPDATE:(.+)')
		fps_message = re.compile(r'FPS:(.+);(.+);')
		
		running = 1
		while running:
		
			line = sys.stdin.readline()
			line = line.rstrip('\n')
			if "QUIT" == line:
				break
			
			if line:
				if re.match(update_message, line):
					self.gui_handler.updateGui(line)
				
				elif re.match(fps_message, line):
					(fps_in, fps_out) = fps_message.search(line).groups()
					self.gui_handler.frame_rate_in = fps_in
					self.gui_handler.frame_rate_out = fps_out
				
				else:
					print line


if __name__ == "__main__":
	app = wx.PySimpleApp(0)
	wx.InitAllImageHandlers()
	frame_1 = GUI(None, -1, "")
	
	gui_handler = MolVizGui(frame_1)
	gui_handler.start()
	
	input_handler = InputHandler(gui_handler, frame_1)
	input_handler.start()
	
	app.SetTopWindow(frame_1)
	frame_1.Show()
	app.MainLoop()
	
	
	
	
	
